/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.sentry.commons.http;

import org.apache.http.Consts;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 简单的POST请求执行器，请求的参数是String, 返回的结果也是String
 *  
 * @author WuBo (wub1@minshenglife.com)
 *
 */
public class SimplePostRequestExecutor implements
        RequestExecutor<String, String> {


    private Charset charset = Consts.UTF_8;

    public SimplePostRequestExecutor(String charset) {
        this.charset = Charset.forName(charset);
    }

    public SimplePostRequestExecutor() {}

    @Override
    public String execute(CloseableHttpClient httpclient, String uri,
            String postEntity) throws ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(uri);

        if (postEntity != null) {
            StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
            httpPost.setEntity(entity);
        }

        CloseableHttpResponse response = httpclient.execute(httpPost);
        String responseContent =
                CharsetResponseHandler.HANDLERS.get(this.charset)
                        .handleResponse(response);
        return responseContent;
    }

}
